package com.joven.shelltest.utils.pdf;

import com.joven.shelltest.utils.WaterMarkAddUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author wzj
 * @Date 2023-08-30 09:14
 **/
public class Pdf2ImgUtil {

    public static void pdfToImage(String urlPath, String watermarkText) {
        InputStream inputStream = null;
        try {
            URL url = new URL(urlPath);
            URLConnection con = url.openConnection();
            con.setConnectTimeout(5000);
            con.setReadTimeout(5000);
            inputStream = con.getInputStream();
//            inputStream = url.openStream();
            pdfToImageDeal(inputStream, watermarkText);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void pdfToImageDeal(InputStream inputStream, String watermarkText) {
        try {
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            //获取pdf的页数
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                //方式1-第二个参数是设置缩放比(即像素)，方式2-renderer.renderImageWithDPI(i, 10)
                BufferedImage image = renderer.renderImage(i, 1.8f);
//                String classpath = Objects.requireNonNull(Class.class.getResource("/")).getPath().replaceFirst("/", "").replaceAll("WEB-INF/classes/", "");
//                String uuid = UUID.randomUUID().toString().replace("-", "");
//                String path = classpath + "p616807/" + uuid + ".png";
//                File file = new File(path);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", baos);
                InputStream is = new ByteArrayInputStream(baos.toByteArray());

                Image srcImg = ImageIO.read(is);

                int srcImgWidth = srcImg.getWidth(null);
                int srcImgHeight = srcImg.getHeight(null);
                //以图片宽高中短的一边为基准长度，控制水印的大小
                int baseLength = (srcImgHeight + srcImgWidth) / 2;
                BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
                //创建画笔
                Graphics2D g = bufImg.createGraphics();
                //srcImg 为上面获取到的原始图片的图片对象
                g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
                //设置字体大小，大小根据图片尺寸变化，最小为30+文字长度
                int fontSize = Math.max(baseLength / 20, 30 + watermarkText.length());
                int textLength = g.getFontMetrics(g.getFont()).charsWidth(watermarkText.toCharArray(), 0, watermarkText.length());
                //自适应文字大小
                fontSize = (int) (fontSize - textLength * 0.2);
                int fontLength = fontSize * (watermarkText.length() + 4);
                //水印图片的宽
                int watermarkImageWidth = (int) (fontLength * 0.7);
                //水印图片的高
                int watermarkImageHeight = fontLength / 2;
                BufferedImage watermarkImage = new BufferedImage(watermarkImageWidth, watermarkImageHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D rotatedG2d = watermarkImage.createGraphics();
                //设置背景为透明
                watermarkImage = rotatedG2d.getDeviceConfiguration().createCompatibleImage(watermarkImageWidth, watermarkImageHeight, Transparency.TRANSLUCENT);
                rotatedG2d.dispose();
                //开始绘制水印文字
                rotatedG2d = watermarkImage.createGraphics();
                rotatedG2d.setFont(new Font("微软雅黑", Font.PLAIN, fontSize));
                //文字自适应图片颜色
                rotatedG2d.setColor(getMarkColor(bufImg, srcImgWidth, srcImgHeight));
                double halfWidth = watermarkImageWidth / 2.0;
                //水印文字逆时针旋转30°
                rotatedG2d.rotate(Math.toRadians(-30), halfWidth, watermarkImageHeight / 2.0);
                rotatedG2d.drawString(watermarkText, (int) (fontSize * 0.1), (int) (watermarkImageHeight / 1.75));
                rotatedG2d.dispose();
                //第一个水印的起始位置
                int startX = 0;
                int startY = (int) (-halfWidth);
                //循环添加水印
                for (int posX = startX; posX <= srcImgWidth; posX += watermarkImageWidth) {
                    for (int posY = startY; posY <= srcImgHeight; posY += watermarkImageHeight) {
                        //将绘制的水印文字图片画到原图片
                        g.drawImage(watermarkImage, posX, posY, null);
                    }
                }
                g.dispose();


                ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
                try {
                    ImageIO.write(bufImg, "jpg", baosOut);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //转换成字节
                byte[] bytes = baosOut.toByteArray();
                BASE64Encoder encoder = new BASE64Encoder();
                //转换成base64串
                String pngBase64 = encoder.encodeBuffer(bytes).trim();
                //删除 \r\n
                pngBase64 = pngBase64.replaceAll("\n", "").replaceAll("\r", "");
                System.out.println("data:image/base64:" + pngBase64);
                System.out.println("添加水印完成");
                System.out.println("-------success-------");
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Color getMarkColor(BufferedImage bi, int w, int h) {
        long sumR = 0;
        long sumG = 0;
        long sumB = 0;
        for (int x = 0; x < w; x++) {
            for (int y = 0; y < h; y++) {
                Color pixel = new Color(bi.getRGB(x, y));
                sumR += pixel.getRed();
                sumG += pixel.getGreen();
                sumB += pixel.getBlue();
            }
        }
        int num = w * h;
        int markColor = (int) (sumR / num + sumG / num + sumB / num) / 3;
        int halfRgb = 128;
        if (markColor < halfRgb) {
            markColor = markColor - 50 < 0 ? markColor + 50 : markColor - 50;
        } else {
            markColor = markColor + 50 > 255 ? markColor - 50 : markColor + 50;
        }
        return new Color(markColor, markColor, markColor, 100);
    }

    /**
     * pdf流 多页转图片
     * @param inputStream /
     * @param heightOffset 图片中间的间距
     * @return pngBase64
     */
    public static String pdfFileToImage(InputStream inputStream, int heightOffset) {
        try {
            InputStream byteInputStream = null;
            try {
                PDDocument doc = PDDocument.load(inputStream);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();
                List<BufferedImage> list = new ArrayList<>();
                if (pageCount > 0) {

                    int totalHeight = 0;
                    int width = 0;

                    for (int i = 0; i < pageCount; i++) {
                        BufferedImage image = renderer.renderImage(i, 1.25f);
                        list.add(image);
                        totalHeight += image.getHeight();
                        if (width < image.getWidth()) {
                            width = image.getWidth();
                        }
                        image.flush();
                    }

                    BufferedImage tag = new BufferedImage(width, totalHeight, BufferedImage.TYPE_INT_RGB);
                    tag.getGraphics();
                    Graphics g = tag.createGraphics();
                    int startHeight = 0;
                    for (BufferedImage image : list) {
                        g.drawImage(image, 0, startHeight, width, image.getHeight(), null);
                        g.drawImage(image, 0, startHeight, width, image.getHeight(), null);
                        startHeight += image.getHeight() + heightOffset;
                    }
                    g.dispose();

                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
                    ImageIO.write(tag, "png", imOut);
                    byteInputStream = new ByteArrayInputStream(bs.toByteArray());
                    byteInputStream.close();

                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            return WaterMarkAddUtils.waterMarkAdd2(byteInputStream, "joven2500");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
